package com.TechMahindra.wx.service.impl;

import com.TechMahindra.wx.bean.WxToken;
import com.TechMahindra.wx.common.QywxPropertieKeys;
import com.TechMahindra.wx.entity.response.AccessTokenResponse;
import com.TechMahindra.wx.utils.DateUtils;
import com.TechMahindra.wx.utils.HttpClientUtil;
import com.TechMahindra.wx.utils.PropertiesUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * access_token 业务逻辑类
 * @author weican
 */
public class AccessTokenService {

	private static Logger log = LoggerFactory.getLogger(AccessTokenService.class);
	
	private AccessTokenService(){};

	private static Map<String, WxToken> tokenMap = new HashMap<>();

	// token超时时间(单位：秒)
	private static int accessTokenTimeOut = 7100;

	
	/**
	 * 获取accessToken
	 * @return 成功返回token，失败返回null
	 */
	public static String getAccessToken(String corpsecret) {
		boolean isGetToke = checkTokenTimeOut(corpsecret);
		String accessToken = "";
		log.info("isGetToke = " + isGetToke);
		if (isGetToke) {
			String response = HttpClientUtil.getInstance().sendHttpGet(String.format(PropertiesUtil.getValue(QywxPropertieKeys.access_token), PropertiesUtil.getValue(QywxPropertieKeys.corpID), corpsecret));
			log.info(response);
			AccessTokenResponse atr = JSON.parseObject(response, AccessTokenResponse.class);
			if (atr.getErrcode() == 0) {
				WxToken token = new WxToken();
				token.setAccessToken(atr.getAccess_token());
				token.setCacheDateTnterval(DateUtils.addDateSecond(new Date(), accessTokenTimeOut));
				tokenMap.put(corpsecret, token);
				accessToken = atr.getAccess_token();
			} else {
				log.info("errorCode：{}, errorMsg：{}", atr.getErrcode(), atr.getErrmsg());
			}
		} else {
			WxToken token = tokenMap.get(corpsecret);
			if (token !=null){
				accessToken =  token.getAccessToken();
			}
		}
		return accessToken;
	}

	/**
	 * 校验token是否需要重新获取，第一次和超过2小时都需要重新获取
	 * @return false 不需要,true需要
	 */
	private static boolean checkTokenTimeOut(String corpsecret) {
		boolean isGetToke = false;
		WxToken token = tokenMap.get(corpsecret);
		if (token == null || token.getCacheDateTnterval() == null) {
			isGetToke = true;
		} else {
			// token超时重新获取
			if (token.getCacheDateTnterval().getTime() <= DateUtils.addDateSecond(new Date(), 0).getTime()) {
				isGetToke = true;
			}
		}
		return isGetToke;
	}

	public static void main(String[] args) {
		getAccessToken(PropertiesUtil.getValue(QywxPropertieKeys.approvalTest_secret));
	}
}
